package com.axun.ckz.mysocketdemo

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.axun.ckz.mysocketdemo.base.BaseActivity
import com.example.vuandroidadsdk.okhttp.CommonOkHttpClient
import com.example.vuandroidadsdk.okhttp.request.CommonRequest
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString

class MainActivity : BaseActivity() {

    lateinit var socket:WebSocket;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        line()
        btn_send.setOnClickListener({
            if (socket.send("dasdsadasd")){

            }else{
                line()
            }
        })
    }

    fun line(){

        CommonOkHttpClient.socket(CommonRequest.createGetRequest("ws://echo.websocket.org",null),object :WebSocketListener(){
            override fun onOpen(webSocket: WebSocket?, response: Response?) {
                super.onOpen(webSocket!!, response)
                socket = webSocket;
                socket.send("hihihi")

            }

            override fun onFailure(webSocket: WebSocket?, t: Throwable?, response: Response?) {
                super.onFailure(webSocket, t!!, response)
                runOnUiThread {
                    val msg:String = tv_content.text.toString()+"\n"+t.message;
                    tv_content.text = msg;

                }
            }

            override fun onClosing(webSocket: WebSocket?, code: Int, reason: String?) {
                super.onClosing(webSocket, code, reason)
                webSocket!!.close(1000,null)
            }

            override fun onMessage(webSocket: WebSocket?, text: String?) {
                super.onMessage(webSocket, text)
                runOnUiThread {
                    val msg:String = tv_content.text.toString()+"\n"+text;
                    tv_content.text = msg;

                }

            }

            override fun onMessage(webSocket: WebSocket?, bytes: ByteString?) {
                super.onMessage(webSocket, bytes)
                runOnUiThread {
                    val msg:String = tv_content.text.toString()+"\n"+bytes
                    tv_content.text = msg;

                }
            }

            override fun onClosed(webSocket: WebSocket?, code: Int, reason: String?) {
                super.onClosed(webSocket, code, reason)
                runOnUiThread {
                    val msg:String = tv_content.text.toString()+"\n"+reason
                    tv_content.text = msg;

                }
            }
        })
    }
}
